import React from 'react'
import {
    Button,
    message,
    Modal
} from 'antd'
import SearchBar from '../../components/SearchBar'
import Table from '../../components/Table'
import {
    FormModal
} from '../../components/ModalForm'
import 'whatwg-fetch'
import API from '../../axios/api'
import {UserType} from "../../utils/system-data";
import {withRouter} from "react-router-dom";
import {inject, observer} from "mobx-react";
const confirm = Modal.confirm


let columns = [
    { dataIndex: 'HallUrl', title: '班级头像', width: 100,render: (text, record) =>  <img src={text} height="40" width="40" /> },
    { dataIndex: 'HallName', title: '班级名称', width: 100,},
    { dataIndex: 'RudderName', title: '分舵名称', width: 100,},
    { dataIndex: 'Address', title: '班级地址', width: 200,},
]
@withRouter @inject('appStore') @observer
class Hall extends React.Component {
    constructor(props) {
        super(props)
        const {user, rudder, rudderList,defaultrudderId,defaultrudderName} = props.appStore
        this.state = {
            user: user,
            rudder: rudder,
            rudderList: rudderList,
            tData: [],
            item: {},
            loading: true,
            modalShow: false,
            modalShowEdit: false,
            addUserShow:false,
            addUserShowItem:false,
            itemInfo:{},
            initHallList:[],
            initUserList:[],
            initUserListItem:[],
            Page: 1,
            Pages:1,
            RudderId:defaultrudderId,
            defaultrudderName:defaultrudderName,
            HallName:'',
            edititem:{}
        }
    }

    componentWillReceiveProps(nextProps){
        const {user, rudder, rudderList} = this.props.appStore
         this.setState({
             user: user,
             rudder: rudder,
             rudderList: rudderList,
             RudderId:user.RudderId
         })
     }
    

    onPageChange = (e) =>{
        this.setState({
            Page:e,
        },()=>{
            this.fetchTableData()
        })
    }

    // 获取表格数据
    fetchTableData =  async (searchFields) => {
        let parms = {
            Page:this.state.Page,
            PageSize: 10,
            RudderId: searchFields && searchFields.RudderId ? searchFields.RudderId : this.state.RudderId,
            HallName: searchFields && searchFields.HallName ? searchFields.HallName :  this.state.HallName,
        }
        await API.fetchHallPages(parms).then((res) => {
            if(res.Code === 200) {
                this.setState({
                    tData: res.Data.List,
                    Pages:res.Data.Pages
                });
            }
            this.setState({
                loading: false
            });
        })
    }

    componentDidMount() {
        this.fetchTableData()
    }

    onSearch = (searchFields) => {
        if(searchFields.RudderId){
            this.setState({
                RudderId:searchFields.RudderId
            })
        }
        if(searchFields.HallName){
            this.setState({
                HallName:searchFields.HallName
            })
        }
        this.setState({
            HallName:searchFields.HallName,
            Page:1
        },()=>{
            this.fetchTableData(searchFields)
        })
       
    }

    searchFields = () => {
        let fields = [{
            title: '班级名称',
            key: 'HallName',
            type: 'input',
        },]
        // if(this.state.user.UserRankType === UserType.ADMIN || this.state.user.RudderId == "-"){
        //     fields = [{
        //         title: '分舵名称',
        //         key: 'RudderId',
        //         type: 'select',
        //         defaultValue: this.state.defaultrudderName,
        //         items: () => this.state.rudderList,

        //     }, ].concat(fields)
        // }
        return fields
    }

    add = () =>{
        this.setState({
            modalShow: true
        })
    }

    onOk = (param) =>{
        param.RudderId = this.state.RudderId
        param.HallGrade = 5
        param.HallUrl = "https://groupst.getgaoding.com/flowbee/000.png"
        API.addHall(param).then(res =>{
            if(res.Code === 200)
            {
                message.success('添加成功')
                this.onCancel()
                this.fetchTableData()
            }
            else message.error(res.Message)
        })
    }
    
    onEditOk = (param) =>{
        param.Id = this.state.edititem.Id
        param.HallGrade = 5
        param.HallUrl = "https://groupst.getgaoding.com/ssjf/ssjflogo.jpg"
        API.editHall(param).then(res =>{
            if(res.Code === 200)
            {
                message.success('修改成功')
                this.onCancel()
                this.fetchTableData()
            }
            else message.error(res.Message)
        })
    }

    onOkadduser = (param) =>{
        param.RankType = UserType.HALL
        API.editInternalUser(param).then(res =>{
            if(res.Code === 200)
            {
                message.success('添加成功')
                this.onCancel()
            }
            else message.error(res.Message)
        })
    }

    onOkadduserItem = (param) =>{
        param.RankType = UserType.HALL
        param.RudderId = this.state.itemInfo.RudderId
        param.HallId =  this.state.itemInfo.Id
        API.editInternalUser(param).then(res =>{
            if(res.Code === 200)
            {
                message.success('添加成功')
                this.onCancel()
            }
            else message.error(res.Message)
        })
    }

    onCancel = () =>{
        this.setState({
            modalShow: false,
            addUserShow: false,
            addUserShowItem:false,
            modalShowEdit:false
        })
    }

    onCancelEdit = () =>{
        this.setState({
            modalShowEdit: false
        })
    }

    tableAction = (actionKey, item) => {
        if (actionKey === 'edit') {
            console.log(item)
            this.setState({
                edititem: item,
                modalShowEdit: true
            })
        } else if (actionKey === 'delete') {
            confirm({
                title: '提示',
                content: '确定删除吗',
                onOk: () => {
                    this.handerDel(item, 0).then(res => {
                        if(res.Code === 200) message.success('删除成功')
                        else message.error(res.Message)
                    })
                    this.fetchTableData()
                },
                onCancel() {}
            })
        }else if(actionKey === 'addUseritem'){
            this.setState({
                itemInfo:item,
                addUserShowItem:true
            })

            this.initUserListItem(item.RudderId)
        }
    }
    initHallList =  async (rudderId) => {
        let params = {
            ...API.config,
            RudderId:  rudderId || this.state.rudder.value,
        }
        await API.fetchHallPages(params).then((res) => {
            let initHallList = []
            if(res.Code === 200) {
                res.Data.List && res.Data.List.map(item => initHallList.push({value: item.Id, mean: item.HallName}))
                this.setState({
                    initHallList
                })
            }
        })
    }

    initUserList =  async (rudderId) => {
        let params = {
            ...API.config,
            RudderId: rudderId || this.state.rudder.value ,
            RankType: -1,
        }
        await API.fetchUserPages(params).then((res) => {
            let _initUserList = []
            if(res.Code === 200) {
                res.Data.List && res.Data.List.map(item => _initUserList.push({value: item.UserId, mean: item.NickName}))
                this.setState({
                    initUserList: _initUserList
                })
            }
        })
    }

    initUserListItem = async (rudderId) => {
        let params = {
            ...API.config,
            RudderId: rudderId || this.state.rudder.value ,
            RankType: -1,
        }
        await API.fetchUserPages(params).then((res) => {
            let _initUserList = []
            if(res.Code === 200) {
                res.Data.List && res.Data.List.map(item => _initUserList.push({value: item.UserId, mean: item.NickName}))
                this.setState({
                    initUserListItem: _initUserList
                })
            }
        })
    }

    rudderChange(v){
        this.initHallList(v)
        this.initUserList(v)
    }

    handerDel(item, status){
        return API.delRole({Id: item.Id, Status: status})
    }

    adduser = () => {
        this.setState({
            addUserShow:true
        })
    }

    fields = () => {
        let fields = [
            { label: '班级名称', type: 'input', name: 'HallName',
                options: {
                    rules: [
                        { required: true, message: '班级名称必填!',}
                    ]
                }
            },
            { label: '班级地址', type: 'input', name: 'Address',
                options: {
                    // rules: [
                    //     { required: true, message: '班级地址必填!',}
                    // ]
                }
            },
            { label: '地址纬度', type: 'input', name: 'Longitude',
                options: {
                    // rules: [
                    //     { required: true, message: '纬度必填!',}
                    // ]
                }
            },
            { label: '地址经度', type: 'input', name: 'Latitude',
                options: {
                    // rules: [
                    //     { required: true, message: '经度必填!',}
                    // ]
                }
            },
            { label: '获取地址经度', type: 'getLongitude', name: 'Latitudez',  

            },
        ]
        // if(this.state.user && this.state.user.UserRankType === UserType.ADMIN  || this.state.user.RudderId == "-"){
        //     fields =  [{
        //         label: '分舵信息',
        //         type: 'select',
        //         name: 'RudderId',
        //         defaultValue:this.state.defaultrudderId,
        //         items: () => this.state.rudderList,
        //           options: {
        //             rules: [{
        //                 required: true,
        //                 message: '必选!',
        //             }]
        //         }
        //     },].concat(fields)
        // }
        return fields
    }


    fieldsedit = () => {
        let that = this;
        let fields = [
            { label: '班级名称', type: 'input', name: 'HallName',

                options: {
                    rules: [
                        { required: true, message: '班级名称必填!',}
                    ],
                    initialValue:that.state.edititem.HallName
                }
            },
            { label: '班级地址', type: 'input', name: 'Address',
                options: {
                    // rules: [
                    //     { required: true, message: '班级地址必填!',}
                    // ],
                    initialValue:that.state.edititem.Address
                }
            },
            { label: '地址纬度', type: 'input', name: 'Longitude',
                options: {
                    // rules: [
                    //     { required: true, message: '纬度必填!',}
                    // ],
                    initialValue:that.state.edititem.Longitude

                }
            },
            { label: '地址经度', type: 'input', name: 'Latitude',
                options: {
                    // rules: [
                    //     { required: true, message: '经度必填!',}
                    // ],
                    initialValue:that.state.edititem.Latitude

                }
            },
            { label: '获取地址经度', type: 'getLongitude', name: 'Latitudet',
          
        },
        ]
        return fields
    }

    fieldsaddUser  = () => {
        let fields = [
            { label: '用户', type: 'select', name: 'UserId',
                showSearch: true,
                items: () =>  this.state.initUserList,
                options: {
                    rules: [
                        { required: true, message: '用户必填!',}
                    ]
                }
            },
            {
                label: '班级',
                type: 'select',
                name: 'HallId',
                items: () => this.state.initHallList,
                options: {
                    rules: [{
                        required: true,
                        message: '权限类型必输!',
                    }]
                }
            },
            { label: '真实姓名', type: 'input', name: 'RealName',
                options: {
                    rules: [
                        { required: true, message: '真实姓名必填!',}
                    ]
                }
            },
            { label: '微信号', type: 'input', name: 'WXQRCode',
                options: {
                    rules: [
                        { required: true, message: '微信号必填!',}
                    ]
                }
            },
            { label: '手机号', type: 'input', name: 'CellPhone',
                options: {
                    rules: [
                        { required: true, message: '手机号必填!',}
                    ]
                }
            },
        ]
        if(this.state.user.UserRankType === UserType.ADMIN || this.state.user.RudderId == "-") {
            fields = [{
                label: '分舵',
                type: 'select',
                name: 'RudderId',
                items: () => this.state.rudderList,
                options: {
                    onChange:(value) => this.rudderChange(value),
                    rules: [{
                        required: true,
                        message: '必选!',
                    }]
                }
            },].concat(fields)
        }
        return fields
    }


    fieldsaddUserItem  = () => {
        let fields = [
            { label: '用户', type: 'select', name: 'UserId',
                showSearch: true,
                items: () =>  this.state.initUserListItem,
                options: {
                    rules: [
                        { required: true, message: '用户必填!',}
                    ]
                }
            },
            { label: '真实姓名', type: 'input', name: 'RealName',
                options: {
                    rules: [
                        { required: true, message: '真实姓名必填!',}
                    ]
                }
            },
            { label: '微信号', type: 'input', name: 'WXQRCode',
                options: {
                    rules: [
                        { required: true, message: '微信号必填!',}
                    ]
                }
            },
            { label: '手机号', type: 'input', name: 'CellPhone',
                options: {
                    rules: [
                        { required: true, message: '手机号必填!',}
                    ]
                }
            },
        ]
        return fields
    }

    render() {
        return (
            <div id="wrap">
                <SearchBar
                    onSubmit={this.onSearch}
                    fields={this.searchFields()}
                />
                <div style={{ paddingTop: 10 }}>
                    <Button  type="primary" onClick={this.add}>添加班级</Button>
                </div>

                <div className="tableBox">
                    <div style={{ paddingTop: 10 }}>
                        <Table
                            onCtrlClick={ this.tableAction }
                            pagination={ true }
                            pageSize={10}
                            header={ columns }
                            data={ this.state.tData }
                            loading={ this.state.loading }
                            scroll={{y: 385 }}
                            action={row => [
                                { key: 'edit', name: '修改信息', color: 'blue', icon: 'edit'},
                            ]}
                            total={this.state.Pages}
                            onChange={this.onPageChange}
                            currentPage={this.state.Page}
                        />
                    </div>
                </div>
                <FormModal
                    modalKey="add"
                    visible={this.state.modalShow}
                    title="添加"
                    fields={this.fields()}
                    onOk={this.onOk}
                    onCancel={this.onCancel}
                    okText="保存"
                    custom="a"
                />

                <FormModal
                    modalKey="add"
                    visible={this.state.addUserShow}
                    title="添加班主任"
                    fields={this.fieldsaddUser()}
                    onOk={this.onOkadduser}
                    onCancel={this.onCancel}
                    okText="保存"
                />

                <FormModal
                    modalKey="add"
                    visible={this.state.addUserShowItem}
                    title="添加班主任"
                    fields={this.fieldsaddUserItem()}
                    onOk={this.onOkadduserItem}
                    onCancel={this.onCancel}
                    okText="保存"
                />

                {/**编辑班级 */}
                <FormModal
                    modalKey="edit"
                    visible={this.state.modalShowEdit}
                    title="修改"
                    fields={this.fieldsedit()}
                    onOk={this.onEditOk}
                    onCancel={this.onCancel}
                    okText="保存"
                    custom="a"
                />
            </div>
        )
    }
}
export default Hall
